#include "uart.h"

void init_rs232()
{
	UCSRC = ( 1 << URSEL )|(1 << UCSZ1)|(1 << UCSZ0);
	UCSRB = ( 1 << TXEN )|( 1 << RXEN )|( 1 << RXCIE );
	UBRRH = (unsigned char) UART_UBRR_CALC(UART_BAUD_RATE, F_CPU) >> 8;
	UBRRL = (unsigned char) UART_UBRR_CALC(UART_BAUD_RATE, F_CPU);
}

uint16_t uart_getc_wait()
{
	while (!(UCSRA & (1 << RXC)));
	return UDR;
}

uint16_t uart_getc()
{
	return (UCSRA & (1 << RXC)) ? (int) UDR : -1;
}

void uart_puts (char *s)
{
	while ((*s) != '\0') {
		uart_putc(*s);
		s++;
	}
}

int uart_putc(unsigned char c)
{
	while (!(UCSRA & (1<<UDRE))) {  // wait until send is complete
	}
 
	UDR = c;                      // send char
	return 0;
}

void uart_flush()
{
	unsigned char dummy;
	while ( UCSRA & (1<<RXC)) dummy = UDR;
}

